<?php

/**
 * Erra_Fields_MultiLevelMenu - Displays hidden field in a form
 *
 * @package
 * @author Alexis Eric
 * @copyright Copyright (c) 2012 - Erra Prod
 * @version $1.0$
 * @access public
 */
class Erra_Fields_MultiLevelMenu extends Erra_Fields_Base_Field {

    function __construct($objectId) {
        parent::__construct($objectId);
    }

    /*
     * 
     */

    public function recursiveDisplay($input) {
        $res = '';
        if (is_array($input)) {
            foreach ($input as $value) {
                $res .= '<li>';
                if (isset($value['children']) && is_array($value['children'])) {
                    $res .= '<a href="#" data-value="' . $value['key'] . '" class="multi-level-item">' . $value['title'] . '</a>';
                    $res .= '<ul>';
                    $res .= $this->recursiveDisplay($value['children']);
                    $res .= '</ul>';
                } else {
                    $res .= '<a href="#" data-label="' . $value['title'] . '" data-value="' . $value['key'] . '" class="multi-level-item">' . $value['title'] . '</a>';
                }
                $res .= '</li>';
            }
        }
        return $res;
    }

    public function getLabel($input) {
        if (strlen($this->getValue())) {
            if (is_array($input)) {
                // Parse normal input
                foreach ($input as $value) {
                    if ($value['key'] == $this->getValue()) {
                        return $value['title'];
                    }
                }
                // Try children and go recursive
                if (isset($value['children']) && is_array($value['children'])) {
                    return $this->getLabel($value['children']);
                }
            }
        }
    }

    /**
     * Erra_Fields_Hidden::editInstance() - Renders an <input type="hidden"> field
     *
     * @param mixed $lang
     * @return
     */
    public function editInstance(Array $extraProperties = null) {
        $res = '<div class="erra-form-field-instance">';
        $res .= $this->outputFieldHeader();
        $res .= '<div class="erra-multilevel-label">';
        $label = strlen($this->getLabel($this->fieldData)) ? $this->getLabel($this->fieldData) : '-';
        $res .= $label;
        $res .= '</div>';
        $res .= '<input type="hidden" name="' . $this->getHtmlName() . '" id="' . $this->getHtmlId() . '" value="' . $this->getRawData() . '" />';
        $res .= '<ul class="erra-multilevel-menu" ' . $this->getHtmlAttributes($extraProperties) . ' data-hidden-id="' . $this->getHtmlId() . '">';
        $res .= $this->recursiveDisplay($this->fieldData);
        $res .= '</ul>';
        $res .= '<div style="clear:both"></div>';
        $res .= '</div>';
        return $res;
    }

}